package com.xiezc.springboot_dht.model;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wb-xzc291800
 */
@Slf4j
public class BeList extends BeObject<List<BeObject>> {

    public BeList() {
        this.value = new ArrayList<>();
    }

    public BeList(List<BeObject> list) {
        this.value = list;
    }

    public void add(BeObject beObj) {
        this.value.add(beObj);
    }

    public void remove(BeObject beObj) {
        this.value.remove(beObj);
    }

    @Override
    public byte[] getContent() {
        if (this.content != null) {
            return this.content;
        }
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            List<BeObject> val = this.value;

            out.write(BeType.list.getPre());
            for (BeObject obj : val) {
                out.write(obj.getContent());
            }
            out.write(BeType.list.getSuffix());
            this.content = out.toByteArray();
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        return this.content;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(getValue());
    }
}
